<template>
  <div>

    <el-container>
      <el-header>
        <el-row :gutter="20" style="padding: 5px 20px;">
          <el-col :span="6"><el-input v-model="searchModel.username" placeholder="请输入内容" clearable @keyup.enter.native="getUserList" /></el-col>
          <el-col :span="6"><el-input v-model="searchModel.phone" placeholder="请输入内容" clearable @keyup.enter.native="getUserList" /></el-col>
          <el-col :span="6"><el-button type="primary" round icon="el-icon-search" @click="getUserList">搜索</el-button></el-col>
          <el-col align="right" :span="6"><el-button type="primary" round icon="el-icon-plus" @click="handleDialogVisible(null)">新增</el-button></el-col>
        </el-row>
      </el-header>

      <el-main>
        <el-table :data="userList" style="width: 100%">
          <el-table-column type="index" label="index" width="180">
            <template slot-scope="scope">
              {{ (searchModel.pageNo - 1) * searchModel.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="id" label="用户编号" width="180" />
          <el-table-column prop="username" label="用户名" width="180" />
          <el-table-column prop="phone" label="电话" />
          <el-table-column prop="status" label="状态">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 1">正常</el-tag>
              <el-tag v-else type="danger">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="handleDialogVisible(scope.row.id)"
              >修改</el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>

      <!-- 分页 -->
      <el-footer>
        <el-pagination
          :current-page="searchModel.pageNo"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="searchModel.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-footer>
    </el-container>

    <!-- 修改框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="clearForm">
      <el-form ref="userFormRef" :model="userForm" :rules="rules">
        <el-form-item prop="username" label="用户名" :label-width="formLabelWidth">
          <el-input v-model="userForm.username" autocomplete="off" />
        </el-form-item>
        <el-form-item v-if="userForm.id == null || userForm.id == undefined" prop="password" label="密码" :label-width="formLabelWidth">
          <el-input v-model="userForm.password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="phone" label="电话" :label-width="formLabelWidth">
          <el-input v-model="userForm.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="status" label="状态" :label-width="formLabelWidth">
          <el-switch
            v-model="userForm.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="用户角色" :label-width="formLabelWidth">
          <el-checkbox-group
            v-model="userForm.roleIdList"
          >
            <el-checkbox v-for="role in roleList" :key="role.roleId" :label="role.roleId">{{ role.roleDesc }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item prop="email" label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="userForm.email" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import userRequest from '@/api/userManage'
import roleRequest from '@/api/roleManage'
export default {
  data() {
    var checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    return {
      totalPage: 0,
      searchModel: {
        username: '',
        phone: '',
        pageNo: 1,
        pageSize: 10
      },
      userList: [],
      dialogFormVisible: false, // 对话框显示隐藏
      userForm: {
        roleIdList: []
      },
      formLabelWidth: '150px',
      title: '',
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 13, message: '长度在 6 到 13 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, message: '邮箱格式错误', trigger: 'blur' }
        ]
      },
      roleList: []
    }
  },
  created() {
    this.getUserList()
    this.getAllRoleList()
  },
  methods: {
    getAllRoleList() {
      roleRequest.getAllRoleList().then(response => {
        this.roleList = response.data
      })
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize
      this.getUserList()
    },
    handleCurrentChange(pageNo) {
      this.searchModel.pageNo = pageNo
      this.getUserList()
    },
    getUserList() {
      // then是调完后的回调方法
      // 在then中把数据传回过来, total 和 list要复制
      userRequest.getUserList(this.searchModel).then(response => {
        this.totalPage = response.data.totalPage
        this.userList = response.data.rows
      })
    },
    handleDialogVisible(id) {
      if (id == null) {
        this.title = '新增用户'
      } else {
        this.title = '修改用户'
        userRequest.getUserById(id).then(response => {
          this.userForm = response.data
        })
      }

      this.dialogFormVisible = true
    },
    clearForm() {
      this.userForm = {
        roleIdList: []
      }
      this.$refs.userFormRef.clearValidate()
    },
    handleSave() {
      // 触发表单验证
      this.$refs.userFormRef.validate((valid) => {
        if (valid) {
          // 提交后台处理
          userRequest.saveUser(this.userForm).then(response => {
            // 成功提示
            this.$message({
              message: response.message,
              type: 'success'
            })
            // 关闭表格
            this.dialogFormVisible = false
            // 刷新表格
            this.getUserList()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleDelete(user) {
      this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userRequest.deleteUserById(user.id).then(response => {
          this.$message({
            type: 'success',
            message: response.message
          })
          this.getUserList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style>
  .el-dialog .el-input {
    width: 70%;
  }
</style>
